package com.ruoyi.web.controller.applets;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.wechat.domain.WechatUser;
import com.ruoyi.wechat.service.IWechatUserService;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

import static com.ruoyi.common.constant.HttpStatus.LOGOUT;

/**
 * 小程序用户接口
 *
 * @author KevenPotter
 * @date 2024-07-18 09:07:11
 */
@RestController
@RequestMapping("/applets/user")
@AllArgsConstructor
public class AppletUserController {

    private final TokenService tokenService;
    private final IWechatUserService wechatUserService;

    /**
     * 查询用户个人中心信息
     *
     * @return 返回是否新增成功
     * @author KevenPotter
     * @date 2024-07-17 09:51:20
     */
    @Anonymous
    @GetMapping("/getPersonalInfo")
    public AjaxResult getPersonalInfo() {
        if (tokenService.checkAppletsToken()) {
            WechatUser loginWechatUser = tokenService.getLoginWechatUser();
            WechatUser realWechatUser = wechatUserService.getById(loginWechatUser.getId());
            return AjaxResult.success(realWechatUser);
        }
        return AjaxResult.error(LOGOUT, "请重新登录");
    }

    /**
     * 修改用户昵称操作
     *
     * @param wechatUser 前端请求
     * @return 返回登录结果
     * @author KevenPotter
     * @date 2024-07-18 09:08:12
     */
    @Anonymous
    @ResponseBody
    @PostMapping(value = "/updateNickname")
    public AjaxResult appletsLogin(@RequestBody WechatUser wechatUser) {
        if (tokenService.checkAppletsToken()) {
            String nickName = wechatUser.getNickName();
            if (StringUtils.isEmpty(nickName)) {
                return AjaxResult.error("未获取到将要修改的昵称信息，请确认后重新提交");
            }
            WechatUser loginWechatUser = tokenService.getLoginWechatUser();
            WechatUser user = wechatUserService.getById(loginWechatUser.getId());
            user.setNickName(nickName);
            return AjaxResult.success(wechatUserService.updateWechatUser(user));
        }
        return AjaxResult.error(LOGOUT, "请重新登录");
    }
}
